package com.wunong.smart.address.domain.operation;

import com.wunong.smart.address.application.request.BaseUserAddressRequest;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户地址操作工厂
 *
 * @author create by zealot.zt
 */
@Component
public class UserAddressOperationFactory implements ApplicationContextAware, SmartInitializingSingleton {

    /**
     * 获取对应的操作
     */
    private static Map<Class<? extends BaseUserAddressRequest>, UserAddressOperation> operations = new ConcurrentHashMap<>();

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserAddressOperationFactory.context = applicationContext;
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, UserAddressOperation> orderOperations = context.getBeansOfType(UserAddressOperation.class);
        if (MapUtils.isNotEmpty(orderOperations)) {
            orderOperations.forEach((k, v) -> operations.put(v.getRequestClass(), v));
        }
    }

    /**
     * 获取对应的操作
     *
     * @param clazz
     * @return
     */
    public static UserAddressOperation getOperation(Class<? extends BaseUserAddressRequest> clazz) {
        return operations.get(clazz);
    }

}
